"""
文件处理工具
提供文件操作相关功能
"""

import os
import hashlib
import logging
from typing import List
from werkzeug.utils import secure_filename
from config import Config

logger = logging.getLogger(__name__)

class FileUtils:
    """文件处理工具类"""
    
    @staticmethod
    def allowed_file(filename: str) -> bool:
        """检查文件类型是否允许"""
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS
    
    @staticmethod
    def generate_filename(original_filename: str) -> str:
        """生成安全的文件名"""
        # 提取文件扩展名
        file_ext = original_filename.rsplit('.', 1)[1].lower() if '.' in original_filename else ''
        
        # 生成MD5哈希作为文件名
        hash_name = hashlib.md5(original_filename.encode()).hexdigest()[:8]
        
        return f"{hash_name}.{file_ext}" if file_ext else hash_name
    
    @staticmethod
    def save_file(file, filename: str) -> str:
        """保存文件"""
        # 确保上传目录存在
        os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
        
        # 使用绝对路径
        upload_dir = os.path.abspath(Config.UPLOAD_FOLDER)
        file_path = os.path.join(upload_dir, filename)
        
        try:
            file.save(file_path)
            logger.info(f"文件保存成功: {file_path}")
            return file_path
        except Exception as e:
            logger.error(f"文件保存失败: {str(e)}")
            logger.error(f"尝试保存到: {file_path}")
            logger.error(f"当前工作目录: {os.getcwd()}")
            raise
    
    @staticmethod
    def delete_file(filename: str) -> bool:
        """删除文件"""
        file_path = os.path.join(Config.UPLOAD_FOLDER, filename)
        try:
            if os.path.exists(file_path):
                os.remove(file_path)
                logger.info(f"文件删除成功: {file_path}")
                return True
            return False
        except Exception as e:
            logger.error(f"文件删除失败: {str(e)}")
            return False
    
    @staticmethod
    def get_file_size(file_path: str) -> int:
        """获取文件大小"""
        try:
            return os.path.getsize(file_path)
        except Exception:
            return 0
    
    @staticmethod
    def ensure_directory(directory: str):
        """确保目录存在"""
        os.makedirs(directory, exist_ok=True)
